const app = getApp();
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    cndUrl: app.domainName,
    tipNum:0,
    isAuth: 1,
    weather:{tem:'',ty:'',pm:'', zwx:'',wuran:'',tylen:''},
    isX:'',
    isSmall:'',
    tianqi:'qing',
    tqid:'',
    txtId:4,
    hasPhone:false,
    userPhone:'',
    isHide:{a:'hide',b:'hide'},
    inpageX:'',
    newOld: 'new',
    wlPath:{},
    goBackId:0,
    loadOZ:'opz',
    openid: app.globalData.openid,
    optionsHashui:'',
    optionsReg:''
  },
  onLoad: function (options) {
    var _this=this;
    //console.log(options)
   // console.log(app.globalData.entryIn)
    if (typeof(options.share) != "undefined" && "" != options.share){
        if(options.share != app.globalData.openid){
          wx.request({ url: app.domainName+'web/?c=isreg',data: {o: app.globalData.openid},header: {'content-type': 'application/json' },success (res) {
               // console.log(res.data.r)
                if(1 == res.data.r){
                  _this.setData({tipNum:8});
                }else{
                    wx.redirectTo({url: '/pages/bei/index?share='+options.share});
                    return;
                }
            }
          });
        }
    }
    if (typeof(options.isnew) != "undefined" && "ok" == options.isnew){ 
       if('sharereg' == app.globalData.entryIn){
        app.globalData.entryIn='';
        _this.setData({tipNum:11});
       }else{
        _this.setData({tipNum:5});
       }
      _this.setData({newOld:'new', isHide:{a:'',b:'hide'}});
    }
    if (typeof(options.isnew) != "undefined" && "sharereg" == options.isnew){  
      _this.setData({newOld:'new', isHide:{a:'',b:'hide'}, tipNum:5});
    }
    if("hashuiok" == app.globalData.entryIn){
      _this.setData({tipNum:8});
    }
    if("hashuinot" == app.globalData.entryIn){
      _this.setData({optionsHashui:'not'});
    }
    this.init();

 
  },
  onShow: function() {
     
  },
  init: function(){
    var _this=this;
    setTimeout(function(){
          wx.login({success (res) {
              app.globalData.loginCode=res.code;
              //console.log(app.globalData.loginCode)
            }})
    }, 1000)
    //console.log(app.globalData.screenHeight);
    if(0 == app.globalData.screenHeight){
      wx.getSystemInfo({
        success: (res) => {
          _screenHeight=res.screenHeight*(750/res.screenWidth);
           if(_screenHeight > 1600){
            _this.setData({isX:'x-', inpageX:'x-'});
          }
        }});
    }else{
      console.log(app.globalData.screenHeight)
        if(app.globalData.screenHeight > 1600){
            _this.setData({isX:'x-', inpageX:'x-'});
        }
 
    }
//console.log(app.globalData.openid)
    if('' == app.globalData.openid){
        wx.getStorage({
          key: 'openid',
          success (res) {
            app.globalData.openid=res.data;
            _this.getisU();
          },
          fail(res){_this.getLogin();}
        })
    }else{
        _this.getisU();
    }
  },
  getisU: function () {
    var _this=this;
    wx.request({ url: app.domainName+'web/?c=isu',data: {o: app.globalData.openid, hashui: _this.data.optionsHashui},header: {'content-type': 'application/json' },success (res) {
      //console.log(res)
        if(2 == res.data.u){
          //_this.setData({ tipNum: 1});
          _this.setData({ isHide:{a:'hide',b:''},loadOZ:'fadeIn animated'});
        }
        if(1 == res.data.u){
          if('goreg' == res.data.g){
            wx.redirectTo({url: '/pages/reg/index?share=goreg'})
          }
          _this.setData({ isAuth: 2 }); //已授权
          _this.setLocation();
          
        }
      }
    });
  },
  setLocation: function(){
    var _this=this;
    wx.getLocation({
      type: 'wgs84',
      success (res) {
        _this.setData({isHide:{a:'',b:'hide'},loadOZ:'fadeIn animated' });
          _this.setWeather(res.latitude,res.longitude);
      },
      fail(res){
        _this.setData({isHide:{a:'',b:'hide'},loadOZ:'fadeIn animated' });
        _this.setWeather('39.91488908', '116.40387397');
      }
     })
  },
  setWeather: function (_al,_on) {
      var _this=this;
      wx.request({ url: app.domainName+'web/?c=getweather',data: {at:_al,  on: _on,op:app.globalData.openid},header: {'content-type': 'application/json' },
      success (res) {
          var _zwx='中等';
          if('晴' == res.data.ty){
            _zwx='强';
          }
          var _tqid='';
          if('xue' != res.data.tq){
            var _rand=Math.floor((Math.random()*10)+1);
            if(_rand > 5){
              _tqid='2';
            }
          }
          var _txtId=1;
          var _pm=res.data.pm;
          if(_pm > 150 && _pm < 201){
            _txtId=2;
          }
          if(_pm > 100 && _pm < 151){
            _txtId=3;
          }
          if(_pm < 101){
            _txtId=4;
          }
          _this.setData({
            loadOZ:'fadeIn animated',
            tianqi:res.data.tq,
            txtId:_txtId,
            tqid:_tqid,
            weather:{
            tem: res.data.tem,ty:res.data.ty,pm:_pm, zwx:_zwx,wuran:res.data.wr, tylen: res.data.ty.length
             }
        });
        wx.request({ url: app.domainName+'web/?c=hasphone',data: {o:app.globalData.openid},header: {'content-type': 'application/json' },
        success (res) {
          // console.log(res.data)
           var _hasPhone=false;
           if('' != res.data.p){
              _hasPhone=true;
           }
           _this.setData({hasPhone:_hasPhone,userPhone:res.data.p });
          
        } });
          if(2 == res.data.isnew){
              wx.request({ url: app.domainName+'web/?c=setweather',data: {at:_al,  on: _on,op:app.globalData.openid},header: {'content-type': 'application/json' },
              success (res) {} });
          }
        }
      });
      setTimeout(function(){
          wx.request({ url: app.domainName+'web/?c=link',data: {o:app.globalData.openid},header: {'content-type': 'application/json' },success (res) {
            if('' == res.data.id){return;}
            var _userInfo = {
              externalId:res.data.id,
              name:res.data.n,
              city:res.data.c,
              country:'中国',
              state: res.data.p,
              wechatInfo: {
                appId:'wxa8d08944f44c4542',
                openId: app.globalData.openid, 
                unionId: res.data.id
              }
            };
            app.linkflow.identify(_userInfo, function() {}, function(){})

          } });
      }, 3000);
 
  },
  decodePhone: function(_code,_iv,_encryptedData){
    var _this=this;
    wx.request({
      url: app.domainName + 'web/?c=getphone',
      method: 'POST',
      data: {op:app.globalData.openid,cd: _code, iv:_iv,encryptedData:_encryptedData
      }, header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) { 
         // console.log(res)
         // console.log(res.data.msg);
          if('404' == res.data.msg){
            wx.login({success (res) {
              app.globalData.loginCode=res.code;
              setTimeout(function(){
                _this.decodePhone(app.globalData.loginCode,_iv,_encryptedData);
              }, 1400);
             
            }});
            return;
          }
          if('200' == res.data.msg){
            _this.setData({hasPhone:true });
             _this.getUser();
          }else{
            wx.redirectTo({url: '/pages/index/index'})
          }
           
      }
    });
  },
  getPhoneNumber: function (e) {
    //console.log(e)
    var _this=this;
     if (typeof(e.detail.iv) != "undefined" || "getPhoneNumber:ok" == e.detail.errMsg){
         wx.checkSession({
          success () {
            _this.decodePhone(app.globalData.loginCode,e.detail.iv,e.detail.encryptedData);
          },
          fail () {
           // console.log('expire');
            wx.login({
              success (res) {
                  app.globalData.loginCode=res.code;
                  _this.decodePhone(app.globalData.loginCode,e.detail.iv,e.detail.encryptedData);
                  
              }})
          }
        })  
     }
  },
  getUser: function () {
    var _this=this;
    wx.request({
      url: app.domainName + 'web/?c=ismember',
      method: 'POST',
      data: {o:app.globalData.openid}, header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) { 
       // console.log(res.data)
        var _msg=res.data.msg;
        app.linkflow.sendEvent({"event": "UDE_403EQIWU8EX","Click_play": "活动主页加入联盟GET惊喜"})
        if('o' == _msg){
        //  console.log(res.data)
          _this.setData({tipNum:3});
          return;
        }
        if('oldjump' == _msg){
          wx.navigateTo({url: '/pages/group/index'})
          return;
        }
        if('reg' == _msg){
          wx.redirectTo({url: '/pages/reg/index'})
          return;
        }
        if('new' == _msg){
          wx.navigateTo({url: '/pages/group/index'})
          return;
        }

      }
    });
  },

  getLogin: function () {
    var _this=this;
    wx.login({
      success (res) {
          wx.request({
            url: 'https://elixir.omnimkt.com/elixir07/web/?c=login',
            data: {cd: res.code},
            header: {'content-type': 'application/json' },
            success (res) {
              app.globalData.openid=res.data.o;
              _this.getisU();
            }
          });
      }})
  },
  doclick: function (e) {
    var _this=this;
    var _id=e.currentTarget.dataset.id;
    if('authnot' == _id){
      this.setData({ tipNum: 0});
      return;
    }
    if('popclose' == _id){
      this.setData({ tipNum: 0});
      return;
    }
    if('yzpopclose' == _id){
      this.setData({ tipNum: 0});
      app.linkflow.sendEvent({"event": "UDE_4033AGK2MTR","Click_inviteetohomepagenew": "被邀请页新会员前往主页加入联盟按钮"})
      return;
    }
    if('beipopclose' == _id){
      this.setData({ tipNum: 0});
      app.linkflow.sendEvent({"event": "UDE_403SMXSXWXO","Click_inviteetohomepageold": "被邀请页老会员前往主页领取福利"})
      return;
    }
    if('popclose3' == _id){
      this.setData({ tipNum: 3});
      return;
    }
    if('openjsuo' == _id){
      this.setData({ tipNum: 2});
      app.linkflow.sendEvent({"event": "UDE_403KQZ90LZQ","Click_saveqr": "常按保存公众号二维码"})
      return;
    }
    if('qingyanghu' == _id){
      this.setData({ tipNum: 7});
      return;
    }
    if('openbaob' == _id){
        wx.request({
          url: app.domainName + 'web/?c=baoda',
          method: 'POST',
          data: {o:  app.globalData.openid
          }, header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: function (res) { 
            if('yes' == res.data.h){
              wx.navigateTo({url: '/pages/prize/index'});
            }else{
              _this.setData({ tipNum: 9});
            }
          }
        });
      return;
    }
    if('oldzuget' == _id){
      wx.navigateTo({url: '/pages/group/index'})
      this.setData({ tipNum: 0});
      app.linkflow.sendEvent({"event": "UDE_403PQXE11GR","Click_play1": "组队页加入联盟GET惊喜"})
      return;
    }
    if('oldzucha' == _id){
      this.setData({ tipNum: 6});
      return;
    }
    if('inpageadd' == _id){
      var _isAuth=this.data.isAuth;
      if(1 == _isAuth){
        this.setData({ tipNum: 1});
      }else{
        this.setData({ isHide:{a:'',b:'hide'}});
      }
      app.linkflow.sendEvent({"event": "UDE_403S6P9VLJL","Click_playstart": "活动说明页加入联盟GET惊喜"})
      return;
    }
    if('chengget' == _id){
      wx.navigateTo({url: '/pages/group/index'})
      app.linkflow.sendEvent({"event": "UDE_403PQXE11GR","Click_play1": "组队页加入联盟GET惊喜"})
      return;
    }
    if('chengchak' == _id || 'beichengchak' == _id ){
      var _goBackId=4;
      if('beichengchak' == _id){
        _goBackId=11;
      }
      wx.request({
        url: app.domainName + 'web/?c=getPath',
        method: 'POST',
        data: {op:  app.globalData.openid
        }, header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function (res) { 
          _this.setData({ tipNum: 4, wlPath:res.data, goBackId:_goBackId});
        }
      });
      return;
    }
    if('closeorder' == _id){
      var _goBackId=this.data.goBackId;
      if(4 == _goBackId){
        this.setData({ tipNum: 5, goBackId:0});
      }else if (11 == _goBackId) {
        this.setData({ tipNum: 11, goBackId:0});
      }else{
        this.setData({ tipNum: 0});
      }
      return;
    }
    if('youfuzhi' == _id){
      wx.setClipboardData({
        data: '￥VsW71xtQ4gB￥',
        success (res) {}})
      return;
    }
    if('youtu' == _id){
      this.saveImg(this.data.cndUrl+'img/reg/youhui-nx.png')
      return;
    }
    console.log(_id);
  },
  bindGetUserInfo (e) {
    var _this=this;
    if (typeof(e.detail.userInfo) != "undefined" || "getUserInfo:ok" == e.detail.errMsg){
      wx.login({
        success (logindata) {
            wx.getUserInfo({
              success: function(res) {
                  wx.request({
                    url: app.domainName + 'web/?c=setuid',
                    method: 'POST',
                    data: {op:  app.globalData.openid, code:logindata.code,iv:res.iv,encryptedData:res.encryptedData
                    }, header: { 'content-type': 'application/x-www-form-urlencoded' },
                    success: function (res) { 
                        if('' !=  res.data.u){
                          /** 
                          var _userInfo = {
                            externalId:res.data.u,
                            name:e.detail.userInfo.nickName,
                            city:e.detail.userInfo.city,
                            country:e.detail.userInfo.country,
                            state: e.detail.userInfo.province,
                            weChatInfo: {
                              appId:'wxa8d08944f44c4542',
                              openId: app.globalData.openid, 
                              unionId: res.data.u
                            }
                          };
                          app.linkflow.identify(_userInfo, function() {}, function(){})
                              */
                        }
                    }
                  });
              }
            })
        }
      })
      
      
      wx.request({
        url: app.domainName + 'web/?c=setuser',
        method: 'POST',
        data: {op:  app.globalData.openid,n: e.detail.userInfo.nickName,
          a: e.detail.userInfo.avatarUrl,sex:e.detail.userInfo.gender,
          p:e.detail.userInfo.province,city:e.detail.userInfo.city,
          hashui: _this.data.optionsHashui
        }, header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function (res) { 
          if('goreg' == res.data.msg){
            wx.redirectTo({url: '/pages/reg/index?share=goreg'})
          }else{
            _this.setData({ tipNum: 0, isAuth: 2});
            _this.setLocation();
          }
          
        }
      });

    }
    app.linkflow.sendEvent({"event": "UDE_403ZFGUFESL","Click_accredit": "授权页立即授权"})
   
  },
  
  
  onReady: function () {

  },
  onShow: function () {

  },
  saveImg(_url){
    let url = _url;
    //用户需要授权
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success:()=> {
              // 同意授权
              this.saveImg1(url);
            },
            fail: (res) =>{
             // console.log(res);
            }
          })
        }else{
          // 已经授权了
          this.saveImg1(url);
        }
      },
      fail: (res) =>{
        console.log(res);
      }
    })   
  },
  saveImg1(url){
    wx.getImageInfo({
      src: url,
      success:(res)=> {
        let path = res.path;
        wx.saveImageToPhotosAlbum({
          filePath:path,
          success:(res)=> { 
            console.log(res);
          },
          fail:(res)=>{
            console.log(res);
          }
        })
      },
      fail:(res)=> {
        console.log(res);
      }
    })
  },
  onShareAppMessage: function (res) {
    return {
      title: '联盟集结令，精致Girl都已经加入就差你了！',
      path: '/pages/index/index?share='+app.globalData.openid,
      imageUrl:'https://elixir.omnimkt.com/elixir07/img/64.png'
    }
  }
})